package com.springboot.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.eduservice.entity.EduSubject;
import com.springboot.eduservice.entity.Subject.OneSubject;
import com.springboot.eduservice.entity.Subject.TwoSubject;
import com.springboot.eduservice.entity.excel.SubjectData;
import com.springboot.eduservice.listener.SubjectExcelListener;
import com.springboot.eduservice.mapper.EduSubjectMapper;
import com.springboot.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-05-11
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    //课程分类树型结构显示
    @Override
    public List<OneSubject> getAllOneTwoSubject(){
        //一级分类
        QueryWrapper<EduSubject> OneQueryWrapper = new QueryWrapper<>();
        OneQueryWrapper.eq("parent_id","0");
        List<EduSubject> onesubjects = baseMapper.selectList(OneQueryWrapper);
        //二级分类
        QueryWrapper<EduSubject> TwoqueryWrapper = new QueryWrapper<>();
        QueryWrapper<EduSubject> TwoSubjectqueryWrapper = TwoqueryWrapper.ne("parent_id", "0");
        List<EduSubject> TwoSubjects = baseMapper.selectList(TwoSubjectqueryWrapper);

        //创建list集合，用于存储最终封装数据
        List<OneSubject> finalSubjectList = new ArrayList<>();


        for (int i = 0;i < onesubjects.size();i++){
            EduSubject subject = onesubjects.get(i);

            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(subject,oneSubject);
            finalSubjectList.add(oneSubject);
            List<TwoSubject> twofinalSubjectList = new ArrayList<>();
            for (int n = 0;n < TwoSubjects.size();n++){
                EduSubject twoSubject = TwoSubjects.get(n);

                if (twoSubject.getParentId().equals(subject.getId())){
                    TwoSubject twoSubject1 = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,twoSubject1);
                    twofinalSubjectList.add(twoSubject1);
                }

            }

            oneSubject.setChildren(twofinalSubjectList);
        }

        return finalSubjectList;

    }
}
